﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.Purchase;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MangoMes.Write.API.Applications.ProductionWorkOrders;
using MediatR;
using MySqlX.XDevAPI.Common;

namespace MangoMes.Write.API.Applications.PurchaseStorags
{
    public class MaterialListHandler : IRequestHandler<MaterialListCommand, PageDTO<MaterialDTO>>
    {
        private readonly IBateRepository<MaterialDTO> material;
        private readonly ILogger<MaterialListHandler> logger;
        public MaterialListHandler(IBateRepository<MaterialDTO> material)
        {
            this.material = material;   
            this.logger = logger;
        }
        /// <summary>
        /// 物料列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async  Task<PageDTO<MaterialDTO>> Handle(MaterialListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                DapperHelper helper = new DapperHelper();
                MaterialDTO materials = new MaterialDTO();
                PageDTO<MaterialDTO> dto = new PageDTO<MaterialDTO>();
                string conn = helper.MangoMesWrite;
                string sql = "SELECT a.MaterialId,a.MaterialNo, productmanage.ProductManageId,productmanage.productManageName,productmanage.productManageNode,productmanage.ProductManageNumber,productmanage.unites,a.Num,a.Batch,warehouselist.StashId,warehouselist.StashName,purchasestorage.ReceiptState,purchasestorage.PurchaseNo FROM material a INNER JOIN productmanage on a.ProductManageId=productmanage.ProductManageId join warehouselist on a.StashId=warehouselist.StashId" +
                    $" join purchasestorage on a.PurchaseNo=purchasestorage.PurchaseNo WHERE purchasestorage.ReceiptState=\"草稿\" and a.PurchaseNo='{request.PurchaseNo}'";
                var res = material.GetAll(sql, materials, conn).ToList();
                dto.TotalCount = res.Count();
                dto.PageCount = (int)Math.Ceiling((res.Count() * 1.0) / request.pageSize);
                dto.Data = res.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                logger.LogInformation("成功");
                return dto;
            }
            catch (Exception ex)
            {
                logger.LogError("失败"+ex);
                throw;
            }

          
        }
    }
}
